package com.chensi.concurrency.zhouyang;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdConsumerDemo {

    public static void main(String[] args) throws InterruptedException {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<String>(10));

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 生产者启动");
            try {
                myResource.prod();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 消费者启动");
            try {
                myResource.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "消费者").start();

        TimeUnit.SECONDS.sleep(5);
        myResource.stop();
        System.out.println("5秒钟到，结束游戏");
    }
}

class MyResource {
    private volatile boolean FLAG = true;

    private AtomicInteger atomicInteger = new AtomicInteger();

    //高手都是定义接口来适配
    BlockingQueue<String> blockingQueue = null;

    //高手都是传接口
    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void prod() throws InterruptedException {
        String data;
        boolean res;
        while (FLAG) {
            data = atomicInteger.incrementAndGet() + "";
            res = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
            if (res) {
                System.out.println(Thread.currentThread().getName() + "\t 成功插入" + data);
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 失败插入" + data);
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t flag变为false，结束生产");
    }

    public void consumer() throws InterruptedException {
        String data;
        while (FLAG) {
            data = blockingQueue.poll(2L, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName() + "\t 成功消费" + data);
        }
        System.out.println(Thread.currentThread().getName() + "\t flag变为false，结束消费");

    }

    public void stop() {
        this.FLAG = false;
    }

}
